﻿app.controller('LessonController', function ($scope, $rootScope, $timeout, $location, notificationFactory, $routeParams, lessonFactory, pictureFactory, messageFactory, wordFactory, systemObjectTagFactory, userRoomFactory, roomFactory, fileFactory) {
    init();

    function init() {
        $scope.severFile = mainFileAddress;
        $scope.roleByGroup = JSON.parse(localStorage.getItem("menu"));
        $scope.userName = $rootScope.userName;
        // xóa thông báo tin nhắn mới của phòng này
        notificationFactory.deleteNotification({ From: localStorage.getItem("idkey"), RoomId: $routeParams.roomId }).success(function () {
            notificationFactory.countAddFriend(localStorage.getItem("idkey")).success(function (data) {
                $scope.countAddFriend = data;
            });
            notificationFactory.countFromRoom(localStorage.getItem("idkey")).success(function (data) {
                $scope.countFromRoom = data;
            });
            notificationFactory.countNewMessage(localStorage.getItem("idkey")).success(function (data) {
                $scope.countNewMessage = data;
            });
        }).error(function () {
            notificationFactory.countAddFriend(localStorage.getItem("idkey")).success(function (data) {
                $scope.countAddFriend = data;
            });
            notificationFactory.countFromRoom(localStorage.getItem("idkey")).success(function (data) {
                $scope.countFromRoom = data;
            });
            notificationFactory.countNewMessage(localStorage.getItem("idkey")).success(function (data) {
                $scope.countNewMessage = data;
            });
        });

        $scope.showSetting = false;
        lessonFactory.getLessonDetail($routeParams.lessonId).success(function (data) {
            $scope.lessonDetail = data;
        });
        //room infomation-------------------------------------------------------------
        roomFactory.getRoom($routeParams.roomId).success(function (data) {
            $scope.roomItem = data;
        });
        userRoomFactory.getUserByRoom($routeParams.roomId).success(function (data) {
            $scope.userInRoom = data;
        });
        //--nội dung bài học---------------------------------------------------------------------
        pictureFactory.getPictureByLesson($routeParams.lessonId).success(function (data) {
            $scope.getPictureByLesson = data;
        });
        wordFactory.getWordByLesson($routeParams.lessonId).success(function (data) {
            $scope.getWordByLesson = data;
        });
        //tag---------------------------------------------------------------------
        systemObjectTagFactory.getTagByLesson($routeParams.lessonId).success(function (data) {
            $scope.getTagByLesson = data;
        });

        //message---------------------------------------------------------------------
        messageDuration();

        $scope.messageData = { CommentText: "", CreateBy: null, RoomId: $routeParams.roomId, DateTime: null, UserId: localStorage.getItem("idkey") };
        $scope.createComment = function () {
            messageFactory.addMessage($scope.messageData).success(function () {
                $scope.messageData.CommentText = "";
                $('#commentTextArea').value = "";
                messageFactory.getMessageByRoom($routeParams.roomId).success(function (data) {
                    $scope.MessageByRoom = data;
                });
            });
            notificationFactory.postNotification({ RoomId: $routeParams.roomId, Type: notificationType.NewComment, From: localStorage.getItem("idkey") });
        };
        $scope.selectPicture = function () {
            navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                quality: 50,
                destinationType: destinationType.DATA_URL,
                sourceType: pictureSource.PHOTOLIBRARY
            });
        };
        $scope.takePicture = function () {
            navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                quality: 50,
                destinationType: destinationType.DATA_URL
            });
        };


        $scope.delComment = function (id) {
            messageFactory.delMessage(id).success(function (data) {
                if (data.Text != null) {
                    $("#mess_" + id).fadeOut();
                    messageFactory.getMessageByFriend(localStorage.getItem("idkey")).success(function (listmess) {
                        $scope.MessageByUser = listmess;
                    });
                    fileFactory.deleteFile({ Text: data.Text, Path: "Upload" });
                }

            });
        };
        //xu ly du lieu
        $scope.nextLesson = false;
        $scope.joinRoom = false;
        $scope.outRoom = false;
        $scope.chatArea = true;
        $scope.nextLessonClick = function () {
            roomFactory.updateNextLesson($routeParams.roomId).success(function (lessonId) {
                $location.path("/lesson/" + $routeParams.roomId + "/" + lessonId);
            });

        };
        $scope.joinRoomClick = function () {
            userRoomFactory.postUserRoom({
                UserId: localStorage.getItem("idkey"),
                RoomId: $routeParams.roomId
            }).success(function () {
                alert('Đã gửi yêu cầu tham gia phòng!');
            });

        };
        $scope.outRoomClick = function () {
            userRoomFactory.delUserRoomNoId({
                UserId: localStorage.getItem("idkey"),
                RoomId: $routeParams.roomId
            }).success(function () {
                $location.path("/room");
            });
        };
        //xác định kiểu user
        userRoomFactory.checkUserType({
            UserId: localStorage.getItem("idkey"),
            RoomId: $routeParams.roomId
        }).success(function (data) {
            if (data == userType.MasterUser)
                $scope.matterUser = true;
            else {
                if (data == userType.InRoomUser) {
                    $scope.outRoom = true;
                }
                else {
                    $scope.chatArea = false;
                    $scope.joinRoom = true;
                }
            }
        });
        //showSettingClick - thong tin phong, chuyen bai hoc
        $scope.showSettingClick = function () {
            $scope.showSetting = !$scope.showSetting;
        };
        //xu ly slide hinh anh
        $scope.direction = 'left';
        $scope.currentIndex = 0;

        $scope.setCurrentSlideIndex = function (index) {
            $scope.direction = (index > $scope.currentIndex) ? 'left' : 'right';
            $scope.currentIndex = index;
        };

        $scope.isCurrentSlideIndex = function (index) {
            return $scope.currentIndex === index;
        };

        $scope.prevSlide = function () {
            $scope.direction = 'left';
            $scope.currentIndex = ($scope.currentIndex < $scope.getPictureByLesson.length - 1) ? ++$scope.currentIndex : 0;
        };

        $scope.nextSlide = function () {
            $scope.direction = 'right';
            $scope.currentIndex = ($scope.currentIndex > 0) ? --$scope.currentIndex : $scope.getPictureByLesson.length - 1;
        };
        $scope.ready = true;
        $scope.updateRoom = function () {
            $scope.loadding = true;
            var complete = true;
            roomFactory.putRoom($scope.roomItem).success(function (data) {
                if (data > 0) complete = false;
            });


            $scope.loadding = false;
            $scope.submitComplie = complete;
        };
        $scope.deleteUserInRoom = function (friend) {
            var result = confirm("Xóa " + friend.FriendName + " ra khỏi phòng?");
            if (result == true) {
                userRoomFactory.delUserRoom(friend.Id);
                $("#friend_" + friend.Id).fadeOut(500);
            }
        };
        //xoa phong, xoa thanh vien trong phong, chat
        $scope.delRoom = function() {
            var result = confirm("Bạn có chắc chắn muốn xóa phòng?");
            if (result == true) {
                userRoomFactory.delAllUserInRoom($routeParams.roomId);
                messageFactory.delAllChatInRoom($routeParams.roomId);
                notificationFactory.delAllNotificationInRoom($routeParams.roomId);
                roomFactory.delRoomById($routeParams.roomId);
                $location.path('/room');
            }
        };
        $scope.speaking = function (word) {
			var source= 'http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=' + word;
			var audio = new Audio();
			audio.src =source;
			audio.play();
            //speak(word);
        };
        $scope.audioBox = function (id) {
            if ($scope.audioBoxShow == id) {
                $('div[id^=audio_]').css("display", "none");
                $scope.audioBoxShow = 0;
            } else {
                $('div[id^=audio_]').css("display", "none");
                $('#audio_' + id).css("display", "block");
                $scope.audioBoxShow = id;
            }


        };

        $scope.ready = true;
        createMenu();
        $scope.out = function () {
            logout();
        };
    }
    function messageDuration() {
        messageFactory.getMessageByRoom($routeParams.roomId).success(function (data) {
            $scope.MessageByRoom = data;
        });
        if ($location.path().indexOf("/lesson") != -1)
            $timeout(messageDuration, 5000, true);
    }

    function onFail() { }

    function onPhotoDataSuccess(imageData) {
        fileFactory.uploadFile({ Text: imageData, Path: "Upload" }).success(function (data) {
            var item = { CommentText: "", Atack: data.Text, CreateBy: null, RoomId: null, DateTime: null, UserId: localStorage.getItem("idkey") };
            messageFactory.addMessage(item).success(function () {
                messageFactory.getMessageByRoom($routeParams.roomId).success(function (listmess) {
                    $scope.MessageByRoom = listmess;
                });
            });
        });
    }
});